package com.epoint.flinkdemo.state;

import com.epoint.flinkdemo.entity.SenSorReading;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.runtime.state.FunctionInitializationContext;
import org.apache.flink.runtime.state.FunctionSnapshotContext;
import org.apache.flink.streaming.api.checkpoint.CheckpointedFunction;

import java.util.Collections;

public class CountOperatorStateMapFunction implements MapFunction<SenSorReading, Integer>, CheckpointedFunction {

    private Integer count;

    private ListState<Integer> listState;

    @Override
    public Integer map(SenSorReading senSorReading) throws Exception {
        if (count == null) {
            count = 0;
        }
        count++;
        // 更新状态
        listState.update(Collections.singletonList(count));
        return count;
    }

    @Override
    public void snapshotState(FunctionSnapshotContext context) throws Exception {
        listState.clear();
        // 清理之前的
        listState.add(count);
    }

    @Override
    public void initializeState(FunctionInitializationContext context) throws Exception {
        ListStateDescriptor<Integer> descriptor = new ListStateDescriptor<Integer>("itemCount", Integer.class);

        // 初始化
        listState = context.getOperatorStateStore().getListState(descriptor);

        if (context.isRestored()) {
            listState.get().forEach(item->{
                count = count + item;
            });
        }
    }
}
